import app from '@/config/app'
//公共js，主要做表单验证，以及基本方法封装
export default {
	dev () {
		// #ifdef MP-WEIXIN
		const mb = wx.getMenuButtonBoundingClientRect();
		// #endif
		// #ifdef MP-BAIDU
		const mb = swan.getMenuButtonBoundingClientRect();
		// #endif
		// #ifdef MP-ALIPAY
		const mb = my.hideAddToDesktopMenu();
		// #endif
		const sys = uni.getSystemInfoSync();
		return {
			width: mb.left || sys.windowWidth,
			height: mb.height || 44,
			//略小，避免误差带来的影响
			top: sys.statusBarHeight
		}
	},
	// 统一消息函数
	msg (title: string, icon = 'none', duration = 2000, mask = false) {
		//统一提示方便全局修改
		Boolean(title) && uni.showToast({
			title,
			duration,
			mask,
			icon
		})
	},
	toast(content: string, title = ''){
		uni.showModal({
			title: title,
			content: content,
			showCancel: false,
			confirmColor: '#00B280',
			confirmText: '关闭'
		})
	},
	scan(succ, type = 0){
		const params = {}
		// 只允许通过相机扫码
		// params.onlyFromCamera = true,
		if(type===1){
			params.scanType = ['barCode']
		}
		// 调起条码扫描
		uni.scanCode({
			...params,
			success (res) {
				if (res.errMsg === 'scanCode:ok') {
					succ(res)
				}
				//console.log('条码类型：' + res.scanType);
				// console.log('条码内容：' + res.result);
			}
		})
	},
	// 确认框
	confirm (title: string, succ: any) {
		uni.showModal({
			content: title,
			confirmColor: '#00b280',
			success: e => e.confirm && succ()
		})
	},
	now () {
		return Date.parse(new Date())/1000
	},
	// 获取键值对部分值
	pick (cols = {}, items = []) {
		const data = {}
		items.map(v => {
			cols[v] && (data[v] = cols[v])
		})
		return data
	},
	// 上一页操作
	last(call = (vm: any) => {}, path = ''){
		const pages = getCurrentPages()
		const l = pages.length - 1
		if(l<=0){
			return 0
		}
		if(path == ''){
			if(l>0){
				// #ifdef MP
				pages[l - 1].$vm.route = pages[l - 1].route
				// #endif
				call(pages[l - 1].$vm)
				return 1
			} else {
				return 0
			}
		}
		let i = l
		path = 'pages/' + path
		while(i>=0){
			if(pages[i].route===path){
				// #ifdef MP
				pages[i].$vm.route = pages[i].route
				// #endif
				call(pages[i].$vm)
				return l - i
			}
			i--
		}

		return -1
	},
	rdrto (path, params = {}){
		if (path.search(/^index\/(?!public)/) === 0 && !uni.$store.user.auth) {
			// #ifndef H5
			uni.$store.user.logout()
			// #endif
			// #ifdef H5
			uni.redirectTo({
				url: '/pages/index/public/login'
			})
			// #endif
		} else if (['index', 'cate', 'my', 'cart', 'stob'].includes(path)){
			uni.switchTab({
				url: '/pages/' + path
			})
		} else {
			uni.redirectTo({
				url: '/pages/' + path + uni.$u.queryParams(params)
			})		
		}
	},
	navto (path: string, params = {}){
		if(path.search(/^(index|mall|stob)/) !== 0 && !uni.$store.user.auth){
			// #ifndef H5
			uni.$store.user.logout()
			// #endif
			// #ifdef H5
			uni.navigateTo({
				url: '/pages/index/public/login'
			})
			// #endif
		} else if (['index', 'cate', 'my', 'cart', 'stob'].includes(path)){
			uni.switchTab({
				url: '/pages/' + path
			})
		} else {
			uni.navigateTo({
				url: '/pages/' + path + uni.$u.queryParams(params)
			})
		}
	},
	back (path = '', direct = true) {
		const routes = getCurrentPages()
		const l = routes.length - 1
		if(path=='' && l > 0){
			uni.navigateBack()
			return true
		}
		const p = 'pages/' + path
		for(let i = l; i >= 0; i--){
			if(routes[i].route == p){
				uni.navigateBack({
					delta: l - i
				})
				return true
			}
		}
		path != '' && (direct ? this.rdrto(path) : this.navto(path))
		return false
	},
	preview (urls: string[], current=0, succ=()=>{}) {
		let list = []
		if(typeof(urls) === 'string'){
			list = [app.imgRoot + urls]
		} else {
			list = urls.map(r=>app.imgRoot + (r.img || r.image || r.url || r))
		}
		uni.previewImage({
			urls: list,
			current: current,
			indicator: 'number',
			longPressActions: {
				itemList: ['发送给朋友', '保存图片', '收藏'],
				success (data) {
					succ(data)
				},
				fail () {
				}
			}
		})
	},
	descarte (arr: object[]) {	
		if(arr.length == 0) return []
		if(arr.length == 1) return arr[0].map(r=>[r])
		return [].reduce.call(arr, (col, set) => {
			const res = []
			col.forEach(c => {
				set.forEach(s => {
					const t = [].concat(Array.isArray(c) ? c : [c])
					t.push(s)
					res.push(t)
				})
			});
			return res
		})
	},
	distance(from, to = false) {
		const point = to || uni.$store.location.point
		const radLat1 = from.lat * Math.PI / 180
		const radLat2 = point.lat * Math.PI / 180
		const a = radLat1 - radLat2
		const b = from.lng * Math.PI / 180 - point.lng * Math.PI / 180
		const s = 2 * Math.asin(Math.sqrt(Math.pow(Math.sin(a / 2), 2) + Math.cos(radLat1) * Math.cos(radLat2) * Math.pow(Math.sin(b / 2), 2)))
		return Math.round(s * 6378137)  // 单位米
	}
}